// 获取应用实例
import { transPx, transRpx } from "../../utils/util"
import { list as getList, hasPermission, apply, hot, latest } from '../../api/index'


const app = getApp<IAppOption>()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    nav: ['最近', '全部', '热点'],
    current: 0,
		navHeight: 0,
		list: [],
		directoryId: '',
		title: '',
		pageIndex: 1, pageSize: 20,

    searchHistory: [],
    searchHistoryDefault: [],
    isExpand: false,
    showExpandBtn: false,
    labelLength: 0,
    hideLength: 0
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			navHeight: app.globalData.navHeight + app.globalData.statusHeight + transPx(152 + 80)
		})
    this.readHistory()
	},
  // 导航栏切换
  currentChange(e) {
    const current = e.currentTarget.dataset.index
    this.setData({ current })
    if (current == 0) {
      this.readHistory()
    }
    if (current == 1 || current == 2) {
      this.setData({ title: '', list: [] })
      let search = this.selectComponent('#search')
      search.setData({title: ''})
      wx.showLoading({ title: '',mask: true})
      const { title, directoryId, pageIndex, pageSize } = this.data

      const fn = current == 1 ? latest : hot

      fn().then(res => {
        wx.hideLoading()
        this.setData({
          list: res.data
        })
      }).catch(err => {
        wx.hideLoading()
      })
    }
  },
  isHistoryHeightOverOpenChange() {
    this.setData({
      isHistoryHeightOverOpen: !this.data.isHistoryHeightOverOpen
    })
  },
  // 读取历史纪录
  readHistory() {
    const that = this
    let searchHistory = wx.getStorageSync('searchHistory') || ''
    searchHistory = searchHistory.split('&,?').filter(item => { return item })
    this.setData({
      searchHistory,
      searchHistoryDefault: searchHistory,
      labelLength: searchHistory.length
    })
    wx.nextTick(() => {
      this.init()
    })
  },
  // 设置历史记录
  setHistory(name) {
    let arr_ = wx.getStorageSync('searchHistory')
    arr_ = arr_.split('&,?')
    arr_ = new Set([...arr_, name])
    arr_ = Array.from(arr_)
    arr_ = [...arr_]
    arr_ = arr_.filter(item => { return item })
    arr_ = arr_.join('&,?')
    wx.setStorageSync('searchHistory', arr_)
    if (this.data.current == 0) { this.readHistory() }
  },
  // 历史记录点击
  historyClick(e) {
    let search = this.selectComponent('#search')
    search.setData({title: e.currentTarget.dataset.item})
    this.serach({
      detail: {
        value: e.currentTarget.dataset.item
      }
    })
  },
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
    // 页面被用户分享时执行
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: 'EY汽车知识库，享你所想！'
        })
      }, 2000)
    })
    return {
      title: 'EY汽车知识库',
      path: '/page/index/index',
      promise 
    }
  },
	serach(e) {
    if (!e.detail.value) return
    this.setHistory(e.detail.value)
		this.setData({
			title: e.detail.value,
			isover: false,
      current: 99,
      list: []
		})
		this.getList()
	},
	getList() {
    wx.showLoading({ title: '',mask: true})
		const { title, directoryId, pageIndex, pageSize } = this.data
		getList({ title, directoryId, pageIndex, pageSize }).then(res => {
      wx.hideLoading()
			this.setData({
				list: res.data.rows,
			})
		}).catch(err => {
      wx.hideLoading()
    })
	},
  // 订阅消息开启
  subscriptionsSetting() {
    wx.getSetting({
      withSubscriptions: true,
      success (res) {
        console.log(res)
        if (res.subscriptionsSetting.mainSwitch && !res.subscriptionsSetting.itemSettings) {
          wx.requestSubscribeMessage({
            tmplIds: ['Ew99D7BIEeUItIOnNNU7mgoGa1emqekDaGdOn63bDqw'],
            success (res) { }
          })
        }
      }
    })
  },
	// 下载文件
  down(e) {
    const that = this
    
		if (!wx.getStorageSync('token')) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录？',
        showCancel: true,
        confirmText: '去登录',
        confirmColor: '#FFE501',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            wx.redirectTo({ url: '/pages/login/login' })
          }
        }
      })
      return
    }
    const item = e.currentTarget.dataset.item
    if (item.accessStatus === 1) {
      wx.navigateTo({
        url: `/pages/detail/detail?id=${item.id}&accessStatus=1`
      })
      return
    }
    wx.showLoading({ title: '',mask: true})
    hasPermission({
      documentId: item.id
    }).then(res => {
      wx.hideLoading()
      if (!res.data) {
        wx.showModal({
          title: '提示',
          content: '暂无访问权限，是否申请授权？',
          showCancel: true,
          confirmColor: '#FFE501',
          success: ({ confirm, cancel }) => {
            if (confirm) {
              wx.showLoading({ title: '',mask: true})
              apply({ documentId:item.id }).then(res1 => {
                wx.hideLoading()
                wx.showToast({title: '权限已申请，审核通过后，我们会及时通知您！', icon: 'none'})
                that.subscriptionsSetting()
              }).catch(res => {
                wx.hideLoading()
                that.subscriptionsSetting()
                wx.showToast({title: res.errorMsg, icon: 'none'})
              })
            }
          }
        })
      } else {
        wx.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`
        })
      }
    }).catch(err => {
      wx.hideLoading()
    })
  },
  init () {
    const that = this
    // 找到第三行偏移量一致的元素索引
    wx.createSelectorQuery().selectAll('.search-list').boundingClientRect(function(rects){
      console.log(rects)
      let line_ = 0 // 几行
      let firstLeft = 0
      let labelIndex_ = 0
      let hideLength_ = 0
      for(let i = 0; i < rects.length; i++) {
        if (i === 0) { firstLeft = rects[i].left }
        if (rects[i].left === firstLeft) line_ = line_ + 1
        if (line_ >= 3) {
          labelIndex_ = i;
          that.setData({ showExpandBtn: true }) // 显示按钮
        } else {
          that.setData({ showExpandBtn: false }) // 隐藏按钮
        }
      }
      if (!that.data.showExpandBtn) return
      let labelIndex__ = labelIndex_ - 1

      wx.nextTick(() => {
        console.log('最终确定索引值', labelIndex__)
        for(let i = 0; i <= labelIndex__; i++) {
          console.log(transPx(710))
          console.log(rects[i].id, rects[i].right, rects[i].right +　transPx(55))
          if (rects[i].right +　transPx(55) < transPx(710)) {
            hideLength_ = i
          }
        }
        console.log('隐藏的索引值应该是', hideLength_)
        that.setData({
          hideLength: hideLength_,
          searchHistory: that.data.searchHistoryDefault.slice(0 , hideLength_)
        })

      })
    }).exec()
  },
  changeExpand () {
    this.setData({
      isExpand: !this.data.isExpand,
    })
    wx.nextTick(() => {
      this.setData({
        searchHistory: this.data.isExpand
          ? this.data.searchHistoryDefault
          : this.data.searchHistoryDefault.slice(0 , this.data.hideLength)
      })
    })
    }
})